<template>
  <el-drawer
    v-model="open"
    :size="'100%'"
    title="代码生成修改"
    :with-header="false"
    class="drawer-root"
  >
    <zz-Label :text="'代码生成修改'" class="label-cls"></zz-Label>
    <el-tabs v-model="tab" @tab-click="clickTab">
      <el-tab-pane label="基本信息" name="sheet1">
        <div style="height: calc(100vh - 145px)" v-if="!loadedTableData">
          <zz-Loading :visible="!loadedTableData" />
        </div>
        <zz-Form
          ref="basicInfoRef"
          :model="genTable"
          :rules="basicRules"
          title="基本信息"
          :label-width="100"
          style="margin-top: 10px"
          v-show="tab === 'sheet1'"
          :style="{ display: !loadedTableData ? 'none' : 'block' }"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="表名称" prop="tableName">
                <el-input
                  v-model="genTable.tableName"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表描述" prop="tableComment">
                <el-input
                  v-model="genTable.tableComment"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实体名称" prop="className">
                <el-input
                  v-model="genTable.className"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作者">
                <el-input
                  v-model="genTable.createBy"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input
                  v-model="genTable.remark"
                  placeholder="请输入..."
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </zz-Form>
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="sheet2">
        <div class="column-info" v-show="tab === 'sheet2'">
          <zz-Loading :visible="loading" />
          <zz-Table
            ref="zzTableRef"
            :data="columsData"
            :hasPage="false"
            :key="'editCodeGenTable'"
            :style="{ display: loading ? 'none' : 'block' }"
          >
            <vxe-column
              type="seq"
              title="序号"
              fixed="left"
              width="50"
            ></vxe-column>
            <vxe-column
              field="columnName"
              title="字段列名"
              fixed="left"
              :min-width="100"
            ></vxe-column>
            <vxe-column
              field="columnShowNameNew"
              title="字段显示名称"
              fixed="left"
              :min-width="200"
            >
              <template #default="{ row }">
                <zz-MultiLangInput
                  v-model="row.columnShowNameNew"
                  placeholder="请输入..."
                  clearable
                  :singleLocaleMode="genTable.enableI18n === '0'"
                ></zz-MultiLangInput>
              </template>
            </vxe-column>
            <!-- <vxe-column
              field="columnShowName"
              title="字段显示名称"
              fixed="left"
              :min-width="100"
            >
              <template #default="{ row }">
                <el-input
                  v-model="row.columnShowName"
                  placeholder="请输入..."
                ></el-input>
              </template>
            </vxe-column> -->
            <vxe-column
              field="columnComment"
              title="字段描述"
              fixed="left"
              :min-width="200"
            >
            </vxe-column>
            <vxe-column
              field="columnType"
              title="物理类型"
              :min-width="100"
            ></vxe-column>
            <vxe-column field="javaType" title="Java类型" :min-width="100">
              <template #default="{ row }">
                <el-select
                  v-model="row.javaType"
                  transfer
                  :class-name="'c-el-select'"
                  @change="
                    (newValue, oldValue) =>
                      watchJavaTypeChange(newValue, oldValue, row)
                  "
                >
                  <el-option
                    v-for="item in javaTypeList"
                    :value="item.value"
                    :key="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="javaField" title="Java属性" :min-width="150">
              <template #default="{ row }">
                <el-input
                  v-model="row.javaField"
                  placeholder="请输入Java属性"
                ></el-input>
              </template>
            </vxe-column>
            <vxe-column field="isInsert" title="插入" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isInsert"
                  label="1"
                  :strict="false"
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="isEdit" title="编辑" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isEdit"
                  label="1"
                  :strict="false"
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="isList" title="列表" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isList"
                  label="1"
                  :strict="false"
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="isQuery" title="查询" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isQuery"
                  label="1"
                  :strict="false"
                  @change="
                    (newValue) => watchIsQueryChange(newValue, row.isQuery, row)
                  "
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="queryType" title="查询方式" :min-width="100">
              <template #default="{ row }">
                <el-select
                  v-model="row.queryType"
                  transfer
                  :class-name="'c-el-select'"
                  :disabled="row.isQuery !== '1'"
                >
                  <el-option
                    v-for="item in getFilteredQueryTypes(row)"
                    :value="item.value"
                    :key="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="isRequired" title="必填" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isRequired"
                  label="1"
                  :strict="false"
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="isLink" title="链接字段" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isLink"
                  label="1"
                  :strict="false"
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="isFk" title="是否外键" :min-width="100">
              <template #default="{ row }">
                <vxe-radio
                  v-model="row.isFk"
                  label="1"
                  :strict="false"
                ></vxe-radio>
              </template>
            </vxe-column>
            <vxe-column field="htmlType" title="显示类型" :min-width="100">
              <template #default="{ row }">
                <el-select
                  v-model="row.htmlType"
                  transfer
                  :class-name="'c-el-select'"
                >
                  <el-option
                    v-for="item in htmlTypeList"
                    :value="item.value"
                    :key="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="dictType" title="字典类型" :min-width="100">
              <template #default="{ row }">
                <el-select
                  v-model="row.dictType"
                  transfer
                  filterable
                  clearable
                  :class-name="'c-el-select'"
                >
                  <el-option
                    v-for="item in dictTypeList"
                    :value="item.value"
                    :key="item.value"
                    :label="item.label"
                  ></el-option>
                </el-select>
              </template>
            </vxe-column>
          </zz-Table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="sheet3">
        <zz-Form
          ref="genInfoRef"
          title="生成信息"
          :model="genTable"
          :rules="genRules"
          class="form-cls"
          :labelWidth="100"
          style="margin-top: 10px"
          v-show="tab === 'sheet3'"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生成模板" prop="tplCategory">
                <el-select
                  v-model="genTable.tplCategory"
                  clearable
                  @change="changeTplCategory"
                >
                  <el-option
                    v-for="item in tplCategoryList"
                    :value="item.value"
                    :key="item.key"
                    :label="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="前端类型" prop="tplWebType">
                <el-select v-model="genTable.tplWebType" clearable>
                  <el-option
                    v-for="item in webCategoryList"
                    :disabled="item.value != 'v3-z'"
                    :value="item.value"
                    :key="item.key"
                    :label="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="是否分页" prop="isPage">
                <el-radio-group v-model="genTable.isPage" size="small">
                  <el-radio value="0">否</el-radio>
                  <el-radio value="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否国际化" prop="enableI18n">
                <el-radio-group v-model="genTable.enableI18n" size="small">
                  <el-radio value="0">否</el-radio>
                  <el-radio value="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="动态列" prop="dynamicColumn">
                <template #label>
                  <span style="display: flex; align-items: center">
                    <el-popover
                      placement="top"
                      width="200"
                      trigger="hover"
                      :content="'采用列设置，页面可实现自定义表格偏好'"
                    >
                      <template #reference>
                        <el-icon
                          style="
                            color: #909399;
                            cursor: help;
                            margin-right: 4px;
                          "
                        >
                          <QuestionFilled />
                        </el-icon>
                      </template>
                    </el-popover>
                    <span>{{ "动态列" }}</span>
                  </span>
                </template>
                <el-radio-group v-model="genTable.dynamicColumn" size="small">
                  <el-radio value="0">否</el-radio>
                  <el-radio value="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新增页类型" prop="addType">
                <el-radio-group v-model="genTable.addType" size="small">
                  <el-radio value="0">弹窗</el-radio>
                  <el-radio value="1">抽屉</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表单设计器" prop="designerType">
                <template #label>
                  <span style="display: flex; align-items: center">
                    <el-popover
                      placement="top"
                      width="200"
                      trigger="hover"
                      :content="'默认表单设计器为基础版，选择高级版可以基于拖拽的表单设计器进行构建'"
                    >
                      <template #reference>
                        <el-icon
                          style="
                            color: #909399;
                            cursor: help;
                            margin-right: 4px;
                          "
                        >
                          <QuestionFilled />
                        </el-icon>
                      </template>
                    </el-popover>
                    <span>{{ "表单设计器" }}</span>
                  </span>
                </template>
                <el-radio-group v-model="genTable.designerType" size="small">
                  <el-radio value="0">基础</el-radio>
                  <el-radio value="1">高级</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生成包路径" prop="packageName">
                <el-input
                  v-model="genTable.packageName"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生成模块名" prop="moduleName">
                <el-input
                  v-model="genTable.moduleName"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生成业务名" prop="businessName">
                <el-input
                  v-model="genTable.businessName"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生成功能名" prop="functionName">
                <el-input
                  v-model="genTable.functionName"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生成代码方式" prop="genType">
                <el-radio-group v-model="genTable.genType" size="small">
                  <el-radio value="0">zip压缩包</el-radio>
                  <el-radio value="1" disabled>自定义路径</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级菜单" prop="parentMenu">
                <!-- TODO: 替换为Element Plus的树选择组件 -->
                <el-select
                  v-model="genTable.parentMenuId"
                  placeholder="请选择..."
                  @change="changeParentMenu"
                  clearable
                >
                  <el-option
                    v-for="item in menuTree"
                    :key="item.menuId"
                    :label="item.menuName"
                    :value="item.menuId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="genTable.genType == '1'">
              <el-form-item label="自定义路径" prop="genPath">
                <el-input
                  v-model="genTable.genPath"
                  placeholder="请输入..."
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </zz-Form>
        <zz-Form
          ref="otherInfoRef"
          title="其他信息"
          :model="genTable"
          class="form-cls"
          :labelWidth="100"
          :labelPosition="'right'"
          style="margin-top: 20px"
          v-if="otherInfoIsShow"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="树编码字段" prop="treeCode">
                <el-select v-model="genTable.treeCode" placeholder="请选择">
                  <el-option
                    v-for="(column, index) in columsData"
                    :key="index"
                    :label="column.columnName + '：' + column.columnComment"
                    :value="column.columnName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="树父编码字段" prop="treeParentCode">
                <el-select
                  v-model="genTable.treeParentCode"
                  placeholder="请选择"
                  @change="changeTreeParentCode"
                >
                  <el-option
                    v-for="(column, index) in columsData"
                    :key="index"
                    :label="column.columnName + '：' + column.columnComment"
                    :value="column.columnName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="树名称字段" prop="treeName">
                <el-select v-model="genTable.treeName" placeholder="请选择">
                  <el-option
                    v-for="(column, index) in columsData"
                    :key="index"
                    :label="column.columnName + '：' + column.columnComment"
                    :value="column.columnName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </zz-Form>
        <zz-Form
          ref="linkInfoRef"
          title="关联信息"
          :model="genTable"
          class="form-cls"
          :labelWidth="100"
          :labelPosition="'right'"
          style="margin-top: 20px"
          v-if="linkInfoIsShow"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="关联子表的表名" prop="subTableName">
                <el-select
                  v-model="genTable.subTableName"
                  placeholder="请选择"
                  @change="subSelectChange"
                >
                  <el-option
                    v-for="(table, index) in tables"
                    :key="index"
                    :label="table.tableName + '：' + table.tableComment"
                    :value="table.tableName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联子表的外键字段" prop="subTableFkName">
                <el-select
                  v-model="genTable.subTableFkName"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(column, index) in subColumns"
                    :key="index"
                    :label="column.columnName + '：' + column.columnComment"
                    :value="column.columnName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </zz-Form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div class="drawer-footer">
        <el-button size="default" @click="close">关闭</el-button>
        <el-button class="ml-10" type="primary" size="default" @click="modify"
          >修改</el-button
        >
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import {
  computed,
  onMounted,
  watch,
  ref,
  getCurrentInstance,
  nextTick,
} from "vue";
import { ElMessage } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  system: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["update:modelValue", "query"]);
const open = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

watch(
  open,
  (newValue, oldValue) => {
    if (newValue) {
      init();
    }
  },
  { immediate: true }
);

const tplCategoryList = ref([]);
const webCategoryList = ref([]);
const javaTypeList = ref([]);
const queryTypeList = ref([]);
const htmlTypeList = ref([]);
const dictTypeList = ref([]);
const menuTree = ref([]);

const init = async () => {
  // tplCategoryList.value = proxy.$TOOL.dict.getList("TPL_CATEGORY");
  tplCategoryList.value = [
    { value: "crud", label: "单表(增删改查)" },
    { value: "tree", label: "树表(增删改查)" },
    { value: "sub", label: "主子表(增删改查)" },
  ];
  // webCategoryList.value = proxy.$TOOL.dict.getList("WEB_CATEGORY");
  webCategoryList.value = [
    { value: "v3-z", label: "Vue3 zzView" },
    { value: "v3-e", label: "Vue3 Element Plus" },
    { value: "v3-i", label: "Vue3 IView" },
  ];
  // javaTypeList.value = proxy.$TOOL.dict.getList("JAVA_TYPE");
  javaTypeList.value = [
    { value: "String", label: "String" },
    { value: "Integer", label: "Integer" },
    { value: "Long", label: "Long" },
    { value: "Double", label: "Double" },
    { value: "LocalDate", label: "LocalDate" },
    { value: "LocalDateTime", label: "LocalDateTime" },
    { value: "Boolean", label: "Boolean" },
    { value: "BigDecimal", label: "BigDecimal" },
    { value: "Map<String, Object>", label: "Map<String, Object>" },
  ];

  // queryTypeList.value = proxy.$TOOL.dict.getList("QUERY_TYPE");
  queryTypeList.value = [
    { value: "LIKE", label: "LIKE" },
    { value: "EQ", label: "EQ" },
    { value: "NOT_EQ", label: "NOT-EQ" },
    { value: "GREATER", label: "GREATER" },
    { value: "LESS", label: "LESS" },
    { value: "GREATER_EQ", label: "GREATER_EQ" },
    { value: "LESS_EQ", label: "LESS_EQ" },
    { value: "BETWEEN", label: "BETWEEN" },
  ];

  // htmlTypeList.value = proxy.$TOOL.dict.getList("HTML_TYPE");
  htmlTypeList.value = [
    { value: "input", label: "输入框" },
    { value: "number", label: "数字输入框" },
    { value: "select", label: "下拉选择" },
    { value: "radio", label: "单选框" },
    { value: "checkbox", label: "复选框" },
    { value: "textarea", label: "文本域" },
    { value: "date", label: "日期选择" },
    { value: "datetime", label: "日期时间选择" },
    { value: "time", label: "时间选择" },
    { value: "month", label: "月份选择" },
    { value: "week", label: "周选择" },
    { value: "year", label: "年选择" },
    { value: "file", label: "文件上传" },
    { value: "image", label: "图片上传" },
    { value: "switch", label: "开关" },
    { value: "slider", label: "滑块" },
  ];

  // 获取字典列表
  dictTypeList.value = JSON.parse(proxy.$TOOL.session.get("pDict"));
  dictTypeList.value?.forEach((e) => {
    e.value = e.code;
    e.label = e.name;
  });
  // todo: 获取菜单树
  // await getMenuTree();

  // 重新渲染表格

  nextTick(() => {
    if (zzTableRef.value) {
      console.log("重新刷新");
      // zzTableRef.value.refreshTable();

      // zzTableRef.value.zzTableRef().refreshColumn();
    }
  });
};

onMounted(() => {
  console.log("初始化静态数据");
  // init();
});

const getMenuTree = async () => {
  let param = {
    useSys: "zz-admin",
    roleId: "",
    menuType: "1",
  };
  // TODO: 替换为实际的API调用
  try {
    let res = await proxy.$API.menuManagement.menu.getMenuTree4Bind.post(param);
    if (res.code === "01") {
      menuTree.value = res.data;
    } else {
      ElMessage.error("获取菜单树失败");
    }
  } catch (error) {
    console.error("获取菜单树失败:", error);
    ElMessage.error("获取菜单树失败");
  }
};

const basicInfoRef = ref();
const genInfoRef = ref();

const title = ref("");
const tableId = ref("");
watch(
  tableId,
  (newValue, oldValue) => {
    if (newValue) {
      queryByTableId(newValue);
    }
  },
  { immediate: true }
);

const basicRules = ref({
  tableName: [
    {
      required: true,
      message: "表名称不能为空...",
      trigger: "change",
    },
  ],
  tableComment: [
    {
      required: true,
      message: "表描述不能为空...",
      trigger: "change",
    },
  ],
  className: [
    {
      required: true,
      message: "实体名称不能为空...",
      trigger: "change",
    },
  ],
});

const genRules = ref({
  tplCategory: [
    {
      required: true,
      message: "生成模板不能为空...",
      trigger: "blur",
    },
  ],
  packageName: [
    {
      required: true,
      message: "生成包路径不能为空...",
      trigger: "blur",
    },
  ],
  moduleName: [
    {
      required: true,
      message: "生成模块名不能为空...",
      trigger: "blur",
    },
  ],
  businessName: [
    {
      required: true,
      message: "生成业务名不能为空...",
      trigger: "blur",
    },
  ],
  functionName: [
    {
      required: true,
      message: "生成功能名不能为空...",
      trigger: "change",
    },
  ],
});

const genTable = ref({});
const zzTableRef = ref(null);
const columsData = ref([]);

// 根据javaType类型过滤查询方式选项
const getFilteredQueryTypes = (row) => {
  if (!row.javaType) return queryTypeList.value;

  // 数字类型
  const numberTypes = ["Integer", "Long", "Double", "BigDecimal"];
  // 日期时间类型
  const dateTypes = ["LocalDate", "LocalDateTime"];

  if (row.javaType === "String") {
    // String类型只允许EQ、NOT_EQ、LIKE
    return queryTypeList.value.filter((item) =>
      ["EQ", "NOT_EQ", "LIKE"].includes(item.value)
    );
  } else if (numberTypes.includes(row.javaType)) {
    // 数字类型只允许大小比较
    return queryTypeList.value.filter((item) =>
      ["EQ", "NOT_EQ", "GREATER", "LESS", "GREATER_EQ", "LESS_EQ"].includes(
        item.value
      )
    );
  } else if (dateTypes.includes(row.javaType)) {
    // 日期时间类型只允许大小比较和BETWEEN
    return queryTypeList.value.filter((item) =>
      [
        "EQ",
        "NOT_EQ",
        "GREATER",
        "LESS",
        "GREATER_EQ",
        "LESS_EQ",
        "BETWEEN",
      ].includes(item.value)
    );
  }

  return queryTypeList.value;
};
// 处理列数据的queryType值，确保符合javaType限制
const processColumnsQueryType = (columns) => {
  return columns.map((row) => {
    const validTypes = getFilteredQueryTypes(row);
    const validTypeValues = validTypes.map((item) => item.value);

    // 如果当前queryType不在有效类型列表中，清除它或设置默认值
    if (
      row.isQuery === "1" &&
      row.queryType &&
      !validTypeValues.includes(row.queryType)
    ) {
      // 根据类型设置合适的默认值
      if (row.javaType === "String") {
        row.queryType = "LIKE"; // String默认使用Like
      } else if (
        [
          "Integer",
          "Long",
          "Double",
          "BigDecimal",
          "LocalDate",
          "LocalDateTime",
        ].includes(row.javaType)
      ) {
        row.queryType = "EQ"; // 数值和日期默认使用EQ
      } else {
        row.queryType = ""; // 其他情况清除
      }
    } else if (row.isQuery !== "1") {
      row.queryType = ""; // 未选中查询时清除查询方式
    }

    return row;
  });
};

// 监听javaType变化，自动调整queryType
const watchJavaTypeChange = (newValue, oldValue, row) => {
  if (newValue !== oldValue && row.isQuery === "1") {
    const validTypes = getFilteredQueryTypes({ ...row, javaType: newValue });
    const validTypeValues = validTypes.map((item) => item.value);

    if (row.queryType && !validTypeValues.includes(row.queryType)) {
      // 根据新类型设置合适的默认值
      if (newValue === "String") {
        row.queryType = "LIKE";
      } else if (
        [
          "Integer",
          "Long",
          "Double",
          "BigDecimal",
          "LocalDate",
          "LocalDateTime",
        ].includes(newValue)
      ) {
        row.queryType = "EQ";
      } else {
        row.queryType = "";
      }
    }
  }
};

// 监听isQuery变化，自动清除或设置默认queryType
const watchIsQueryChange = (newValue, oldValue, row) => {
  if (newValue === "1") {
    // 选中查询时，如果没有设置queryType，根据javaType设置默认值
    if (!row.queryType) {
      const validTypes = getFilteredQueryTypes(row);
      if (validTypes.length > 0) {
        // 根据类型选择合适的默认值
        if (row.javaType === "String") {
          row.queryType = "LIKE";
        } else {
          row.queryType = validTypes[0].value;
        }
      }
    }
  } else {
    // 取消查询时，清除queryType
    row.queryType = "";
  }
};

const loadedTableData = ref(false);

const queryByTableId = async (id) => {
  if (!id) {
    return;
  }
  loadedTableData.value = false;
  try {
    let res = await proxy.$API.codeManagement.codeGen.queryByTableId.get(
      props.system,
      id
    );
    if (res.code === "01") {
      loadedTableData.value = true;
      title.value = `修改 ${res.data.tableName} 生成配置`;
      genTable.value = { ...res.data };
      // 处理option
      if (genTable.value.options) {
        let options = JSON.parse(genTable.value.options);
        genTable.value.parentMenuId = options.parentMenuId;
        genTable.value.parentMenuUrl = options.parentMenuUrl;
        genTable.value.treeCode = options.treeCode;
        genTable.value.treeParentCode = options.treeParentCode;
        genTable.value.treeName = options.treeName;
      }
      if (genTable.value.tplCategory) {
        changeTplCategory(genTable.value.tplCategory);
      }
      // 表的列，处理queryType值
      columsData.value = processColumnsQueryType(res.data.columns);
    } else {
      ElMessage.warning("查询有异常，请联系开发者");
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败");
  }
};

const tab = ref("sheet1");
const loading = ref(false);
const clickTab = (tab) => {
  if (tab.paneName === "sheet2") {
    // 点击字段信息标签页时显示loading
    loading.value = true;

    // 由于vxe-table没有渲染完成回调，我们使用setTimeout来模拟
    // 并在多个nextTick后尝试处理表格布局
    let tickCount = 0;
    const maxTicks = 5;

    const checkTableRender = () => {
      nextTick(() => {
        tickCount++;

        if (zzTableRef.value && zzTableRef.value.zzTableRef) {
          try {
            // 尝试重新计算表格布局
            zzTableRef.value.zzTableRef().recalculate(true);
          } catch (e) {
            console.log("表格布局计算失败，稍后重试", e);
          }

          // 即使没有回调，我们也在几次tick后隐藏loading
          if (tickCount >= 3) {
            loading.value = false;
            return;
          }
        }

        // 继续检查直到达到最大次数
        if (tickCount < maxTicks) {
          setTimeout(checkTableRender, 50);
        } else {
          // 达到最大次数后强制隐藏loading
          loading.value = false;
        }
      });
    };

    // 开始检查
    checkTableRender();
  }
};

const otherInfoIsShow = ref(false);
const linkInfoIsShow = ref(false);
const changeTplCategory = (val) => {
  if (val == "tree") {
    otherInfoIsShow.value = true;
    linkInfoIsShow.value = false;
  } else if (val == "sub") {
    linkInfoIsShow.value = true;
    otherInfoIsShow.value = false;
  } else {
    otherInfoIsShow.value = false;
    linkInfoIsShow.value = false;
  }
};

// 监听otherInfoIsShow
watch(otherInfoIsShow, (newValue, oldValue) => {
  if (!newValue) {
    genTable.value.treeCode = "";
    genTable.value.treeParentCode = "";
    genTable.value.treeName = "";
  }
});

const changeParentMenu = (val) => {
  let menusList = proxy.$XEUtils.toTreeArray(menuTree.value);
  let obj = menusList.find((e) => e.menuId === val);
  if (obj) {
    genTable.value.parentMenuUrl = obj.url;
  }
};

const changeTreeParentCode = (val) => {
  // treeParentCode 发生改变，列中对应的字段也需要改变
  if (val) {
    let column = columsData.value.find((e) => e.columnName === val);
    if (column) {
      if (column.isInsert != "1") {
        column.isInsert = "1";
      }
      if (column.isEdit != "1") {
        column.isEdit = "1";
      }
    }
  }
};

// 关联子表
const tables = ref([]);
const subColumns = ref([]);

watch(linkInfoIsShow, (newValue, oldValue) => {
  if (newValue) {
    // 关联子表时，查询所有数据库表
    queryAllTables();
  }
});

// 查询所有表
const queryAllTables = async () => {
  try {
    let res = await proxy.$API.codeManagement.codeGen.queryAll.get(
      props.system
    );
    if (res.code === "01") {
      tables.value = res.data || [];
    } else {
      ElMessage.warning("查询有异常，请联系开发者");
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败");
  }
};

// 关联子表-选择表改变时，查询该表的所有列
const subSelectChange = async () => {
  console.log("genTable.subTableName:", genTable.value.subTableName);
  if (genTable.value.subTableName) {
    let res =
      await proxy.$API.codeManagement.codeGen.queryColumnsByTableName.get(
        props.system,
        genTable.value.subTableName
      );
    if (res.code === "01") {
      subColumns.value = res.data || [];
    } else {
      ElMessage.warning("查询有异常，请联系开发者");
    }
  }
};

// 修改
const modify = async () => {
  // 校验
  let valid1 = await basicInfoRef.value.validate();
  let valid2 = await genInfoRef.value.validate();
  if (!valid1 || !valid2) {
    return;
  }
  let param = genTable.value;
  // 处理optionMap
  param.params = {
    treeCode: genTable.value.treeCode,
    treeName: genTable.value.treeName,
    treeParentCode: genTable.value.treeParentCode,
    parentMenuId: genTable.value.parentMenuId,
    parentMenuUrl: genTable.value.parentMenuUrl,
  };

  // TODO: 替换为实际的API调用
  try {
    let res = await proxy.$API.codeManagement.codeGen.modify.post(
      props.system,
      param,
      localStorage.getItem("language") || "zh-CN"
    );
    if (res.code === "01") {
      ElMessage.success("修改成功");
      close();
      emit("query");
    } else {
      ElMessage.warning("系统异常，请联系开发者");
    }
  } catch (error) {
    console.error("修改失败:", error);
    ElMessage.error("修改失败");
  }
};

const close = () => {
  open.value = false;
  reset();
};

const reset = () => {
  genTable.value = {};
  otherInfoIsShow.value = false;
  linkInfoIsShow.value = false;
  // 重置form表单校验条件
  basicInfoRef.value.resetFields();
  genInfoRef.value.resetFields();
  tab.value = "sheet1";
  tableId.value = "";
};

defineExpose({ title, tableId });
</script>

<style lang="less">
.drawer-root .el-drawer__body {
  overflow: hidden !important;
}
.column-info {
  height: calc(100vh - 145px);
  overflow: auto;
}
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  border-top: 1px solid var(--el-border-color);
  margin: 0 -20px -20px -20px;
}
</style>
